package org.lqq.loadbalance;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import org.lqq.entity.DefaultServerAddress;
import org.lqq.entity.ServerAddress;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by 李清泉 on 2017/10/26.
 *
 * @remark
 */
public class RibbonLoaderBalancer extends AbstractLoadBalancer {

    private IRule rule;

    public RibbonLoaderBalancer(IRule rule) {
        this.rule = rule;
    }

    @Override
    public ServerAddress choose(Collection<ServerAddress> serverAddresses) {
        List<Server> servers = new ArrayList<>();
        for (ServerAddress serverAddress : serverAddresses) {
            Server server = new Server(serverAddress.getHost(), serverAddress.getPort());
            servers.add(server);
        }
        ILoadBalancer loadBalancer = new BaseLoadBalancer();
        loadBalancer.addServers(servers);
        rule.setLoadBalancer(loadBalancer);
        Server server = rule.choose("key");
        if (server != null) {
            return new DefaultServerAddress("name", server.getPort(), server.getHost());
        } else {
            return null;
        }
    }
}
